import os
import sqlite3
from flask import Flask, render_template, jsonify, request, send_from_directory
from datetime import datetime, timedelta
import json
import glob

app = Flask(__name__, static_folder='static', template_folder='templates')

# 数据库路径
DB_PATH = "human_detection.db"

def get_db_connection():
    """获取数据库连接"""
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    return conn

def limit_image_files(folder):
    """限制图片文件夹中的文件数量，最多保留1000张图片"""
    files = glob.glob(f"{folder}/*.jpg")
    if len(files) > 1000:
        # 按文件修改时间排序，删除最旧的文件
        files.sort(key=os.path.getmtime)
        for file in files[:-1000]:  # 保留最新的1000张
            try:
                os.remove(file)
            except:
                pass

@app.route('/')
def index():
    """主页"""
    return render_template('index.html')

@app.route('/api/devices')
def get_devices():
    """获取设备列表"""
    # 读取设备状态文件（如果存在）
    devices = []
    try:
        # 这里应该从server.py中获取设备状态
        # 由于我们在web_interface.py中无法直接访问server.py的devices变量
        # 实际项目中可以通过MQTT或共享内存等方式获取
        # 此处返回模拟数据
        devices = [
            {"id": "user1_1234", "name": "活动追踪器 user1", "status": "online"},
            {"id": "user2_5678", "name": "活动追踪器 user2", "status": "offline"}
        ]
    except Exception as e:
        print(f"获取设备列表失败: {e}")
    
    return jsonify(devices)

@app.route('/api/device_stats')
def get_device_stats():
    """获取设备统计信息"""
    try:
        # 在实际项目中，应该从server.py获取实时设备状态
        # 此处返回模拟数据
        stats = {
            "online": 2,
            "total": 5
        }
        return jsonify(stats)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/daily_summary')
def get_daily_summary():
    """获取每日总结"""
    try:
        conn = get_db_connection()
        # 获取最近7天的总结
        seven_days_ago = (datetime.now() - timedelta(days=7)).strftime("%Y-%m-%d")
        summaries = conn.execute(
            'SELECT * FROM daily_activities WHERE date >= ? ORDER BY date DESC',
            (seven_days_ago,)
        ).fetchall()
        conn.close()
        
        result = []
        for summary in summaries:
            result.append({
                "id": summary["id"],
                "device_id": summary["device_id"],
                "date": summary["date"],
                "summary": summary["summary"],
                "detailed_analysis": summary["detailed_analysis"],
                "created_at": summary["created_at"]
            })
        
        return jsonify(result)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/human_detection_stats')
def get_human_detection_stats():
    """获取人体检测统计信息"""
    try:
        conn = get_db_connection()
        # 获取最近30天的统计数据
        thirty_days_ago = (datetime.now() - timedelta(days=30)).strftime("%Y-%m-%d")
        stats = conn.execute(
            'SELECT date, total_duration, detection_count FROM daily_summary WHERE date >= ? ORDER BY date',
            (thirty_days_ago,)
        ).fetchall()
        conn.close()
        
        dates = []
        durations = []
        counts = []
        
        for stat in stats:
            dates.append(stat["date"])
            durations.append(stat["total_duration"])
            counts.append(stat["detection_count"])
        
        return jsonify({
            "dates": dates,
            "durations": durations,
            "counts": counts
        })
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/screenshots')
def get_screenshots():
    """获取截图列表"""
    try:
        # 限制截图文件夹中的文件数量
        limit_image_files("screenshots")
        limit_image_files("camera_shots")
        limit_image_files("detections")
        
        # 获取截图文件列表
        screenshots = []
        for folder in ["screenshots", "camera_shots", "detections"]:
            files = glob.glob(f"{folder}/*.jpg")
            # 按修改时间排序，获取最新的20张图片
            files.sort(key=os.path.getmtime, reverse=True)
            for file in files[:20]:  # 每个文件夹最多20张
                screenshots.append({
                    "path": file.replace("\\", "/"),
                    "name": os.path.basename(file),
                    "folder": folder,
                    "mtime": os.path.getmtime(file)
                })
        
        # 按时间排序
        screenshots.sort(key=lambda x: x["mtime"], reverse=True)
        
        return jsonify(screenshots[:30])  # 最多返回30张图片
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/screenshots/<path:filename>')
def serve_screenshot(filename):
    """提供截图文件服务"""
    try:
        # 确保文件在允许的目录中
        if filename.startswith(("screenshots/", "camera_shots/", "detections/")):
            directory = filename.split("/")[0]
            file_name = "/".join(filename.split("/")[1:])
            return send_from_directory(directory, file_name)
        else:
            return "文件未找到", 404
    except Exception as e:
        return str(e), 404

@app.route('/manage')
def manage_devices():
    """设备管理页面"""
    return render_template('manage.html')

if __name__ == '__main__':
    # 创建templates和static目录
    os.makedirs('templates', exist_ok=True)
    os.makedirs('static', exist_ok=True)
    os.makedirs('static/css', exist_ok=True)
    os.makedirs('static/js', exist_ok=True)
    
    app.run(host='0.0.0.0', port=8989, debug=True)
```
```
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Web界面模块
提供Flask Web界面功能
"""

from flask import Flask, render_template, jsonify, request
import threading
import time
import os
import sys

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

# 导入项目模块
from config import FLASK_CONFIG
from utils.db_utils import get_db_connection

def create_web_app():
    """创建Flask Web应用"""
    app = Flask(__name__, 
                template_folder='../templates',
                static_folder='../static')
    
    @app.route('/')
    def index():
        """主页"""
        return render_template('index.html')
    
    @app.route('/manage')
    def manage():
        """设备管理页面"""
        return render_template('manage.html')
    
    @app.route('/device/<device_id>')
    def device_detail(device_id):
        """设备详情页面"""
        return render_template('device_detail.html', device_id=device_id)
    
    @app.route('/api/devices')
    def get_devices():
        """获取设备列表API"""
        # 这里应该从实际的设备管理器获取设备列表
        # 目前返回示例数据
        devices = [
            {"id": "user1_1234", "name": "用户1的设备", "status": "online"},
            {"id": "user2_5678", "name": "用户2的设备", "status": "offline"}
        ]
        return jsonify(devices)
    
    @app.route('/api/device_stats')
    def get_device_stats():
        """获取设备统计信息"""
        stats = {
            "online": 1,
            "total": 2
        }
        return jsonify(stats)
    
    return app

def start_web_server():
    """启动Web服务器"""
    app = create_web_app()
    app.run(
        host=FLASK_CONFIG['host'],
        port=FLASK_CONFIG['port'],
        debug=FLASK_CONFIG['debug'],
        use_reloader=False
    )

if __name__ == "__main__":
    start_web_server()
